package iaccounts

import (
	"fmt"

	"gitee.com/djaf/my-certs/app/classes/accounts"
	"gitee.com/djaf/my-certs/app/data/dxo"
	"gitee.com/djaf/my-certs/app/data/entity"
	"github.com/starter-go/security/random"
	"gorm.io/gorm"
)

// DaoImpl ...
type DaoImpl struct {

	//starter:component
	_as func(accounts.DAO) //starter:as("#")

	Agent       dxo.DatabaseAgent  //starter:inject("#")
	UUIDService random.UUIDService //starter:inject("#")

}

func (inst *DaoImpl) _impl() accounts.DAO {
	return inst
}

func (inst *DaoImpl) model() *entity.Account {
	return new(entity.Account)
}

func (inst *DaoImpl) modelList() []*entity.Account {
	return make([]*entity.Account, 0)
}

func (inst *DaoImpl) makeResult(o *entity.Account, res *gorm.DB) (*entity.Account, error) {
	err := res.Error
	if err != nil {
		return nil, err
	}
	return o, nil
}

// Find ...
func (inst *DaoImpl) Find(db *gorm.DB, id dxo.AccountID) (*entity.Account, error) {
	m := inst.model()
	db = inst.Agent.DB(db)
	res := db.First(m, id)
	return inst.makeResult(m, res)
}

// Insert ...
func (inst *DaoImpl) Insert(db *gorm.DB, item *entity.Account) (*entity.Account, error) {

	uuid := inst.UUIDService.Build().Class("entity.Certificate").Generate()

	item.ID = 0
	item.UUID = uuid

	if item.Selector == 0 {
		item.SetAsCurrent(false)
	}

	db = inst.Agent.DB(db)
	res := db.Create(item)
	return inst.makeResult(item, res)
}

// Update ...
func (inst *DaoImpl) Update(db *gorm.DB, id dxo.AccountID, fn func(item *entity.Account)) (*entity.Account, error) {
	return nil, fmt.Errorf("no impl")
}

// Remove ...
func (inst *DaoImpl) Remove(db *gorm.DB, id dxo.AccountID) error {
	return fmt.Errorf("no impl")
}

// List ...
func (inst *DaoImpl) List(db *gorm.DB, q *accounts.Query) ([]*entity.Account, error) {
	return nil, fmt.Errorf("no impl")
}

// FindBySelector ...
func (inst *DaoImpl) FindBySelector(db *gorm.DB, sel int64) (*entity.Account, error) {
	db = inst.Agent.DB(db)
	item := inst.model()
	res := db.Where("selector=?", sel).First(item)
	return inst.makeResult(item, res)
}
